<?php

/**
 * sphinx客户端使用的API
 * @author dcl 2012-04-20
 */
class SphinxApi{
    
    public $area_code;              //地区
    public $cat_code;               //行业分类
    public $search_text;            //搜索内容
    public $url_key;                //密匙
    public $timeout = 30;           //密匙过期时间
    public $timestamp;              //HTTP请求的密匙生成时间
    public $page = 1;               //页码
    public $page_size = 100;        //分页
    public $is_cache = 1;           //是否使用缓存查找数据
    public $sphinx_server = "http://search.dld.com/search/index";//搜索请求的PHP地址 
    public $indexer = "discount";   //指定搜索的数据类型
    public $order_by = '';          //设置排序规则只支持5个字段的排序
    public $group_by = '';			 // GROUP BY(目前只支持cat_code)
    public $x;						 // 经纬度坐标：经度单位（度）
    public $y; 						 // 经纬度坐标：纬度单位（度）
    public $dist;
    private $filter_range;          //设置整型字段的取值范围 
    private $filter_float_range;    //设置浮点型字段的取值范围 
    private $filter;				 //设置属性过滤
    
    
    public function __construct(){
        $this->timestamp = time();
    } 
      
    /**
     * 设置属性过滤
     * $this->addFilter('id', array(1,2,3,4), false) 对应的SQL查询是 id IN (1,2,3,4)
     * $this->addFilter('id', array(1,2,3,4), true) 对应的SQL查询是 id NOT IN (1,2,3,4)
     * @param string	$attribute
     * @param array		$values
     * @param boolean	$exclude
     * */
    public function addFilter($attribute, $values, $exclude = false){
    	$values = is_array($values) ? $values : (array)$values;
    	$this->filter = strtolower(' ' . $attribute . '#' . implode('|' ,$values)  . '#' . (($exclude) ? "true" : "false"));
    }
    
    /**
     * 设置整型字段的取值范围 
     * $this->addFilterRange("publish_time", 0, 1000, false)  对应的SQL查询 是 0 < publish_time AND publish_time < 1000
     * $this->addFilterRange("publish_time", 1000, 2000, true)  对应的SQL查询 是 1000 > publish_time AND publish_time > 2000
     * @param string    $attribute
     * @param int       $min    
     * @param int       $max
     * @param boolean   $exclude        
     */
    public function addFilterRange($attribute, $min, $max, $exclude = false){
        $this->filter_range .= strtolower(' ' . $attribute . '#' . $min . '#' . $max . '#' . (($exclude) ? "true" : "false"));
    }
    
    /**
     * 设置整型字段的取值范围 
     * $this->addFilterFloatRange("publish_time", 1.3, 5.6, false)  对应的SQL查询 是 1.3 < publish_time AND publish_time < 5.6
     * $this->addFilterFloatRange("publish_time", 2.3, 7.5, true)  对应的SQL查询 是 2.3 > publish_time AND publish_time > 7.5
     * @param string        $attribute
     * @param float         $min    
     * @param float         $max
     * @param boolean       $exclude        
     */
    public function addFilterFloatRange($attribute, $min, $max, $exclude = false){
        $this->filter_float_range .= strtolower(' ' . $attribute . '#' . $min . '#' . $max . '#' . (($exclude) ? "true" : "false"));
    }
     
    /**
     * 校验搜索数据的正确
     */
    public function checkData(){
        if($this->search_text == ''){
            return false;
        }
        return true;
    }
    /**
     * 根据HTTP请求的数据生成密匙
     * @return string
     */
    private function createSysKey(){
        $sys_key = Yii::app()->params['models']['sphinxApi']['urlKey'];
        $data = $this->postData();
        $this->url_key = md5(implode("", $data) . $sys_key);
    }
    
    /**
     * API请求数据集合
     * @return array
     */
    private function postData(){
        return array(
                "search_text" => $this->search_text,    // 搜索内容
                "page" => $this->page,                  // 页码
                "page_size" => $this->page_size,        // 每页的数据数
                "order_by" => $this->order_by,          // 排序
                "area_code" => $this->area_code,        // 地区编码
                "indexer" => $this->indexer,            // 搜索的数据类型
                "cat_code" => $this->cat_code,          // 行业分类
                "group_by" => $this->group_by,			// GROUP BY
                "x"			=> $this->x,				// 经纬度坐标：经度单位（度）
        		"y"			=> $this->y,				// 经纬度坐标：纬度单位（度）
        		"dist"      =>$this->dist,
        		"filter"	=>	trim($this->filter),	// 属性过滤
                "filter_range" => trim($this->filter_range),    // 整型取值范围
                "filter_float_range" => trim($this->filter_float_range),  // 浮点型取值范围
                "timestamp" => $this->timestamp         // 时间戳
        ); 
    }


    
    /**
     * 执行请求
     * @return array
     */
    public function excute(){
        $this->createSysKey();
        $httpclient = new HttpClientD ( $this->sphinx_server );
		$httpclient->open ();
        $data = $this->postData();
        $data['url_key'] = $this->url_key;            // 密匙
		$httpclient->setPostData ( $data );
		try{
			$result = $httpclient->excute ();
			if ($result == ''){
				return array("count" => 0, "data" => null);
			}
			$tmp = UtilD::parseResult($result); 
			if(is_array($tmp['keyMain']) && (isset($tmp['keyMain']['data']) || empty($tmp['keyMain']['data'])) && isset($tmp['keyMain']['count'])){
				return $tmp['keyMain'];
			} 
			Yii::log("SphinxError:" . var_export($tmp, true), 'error', 'system.*');  
		}catch(Exception $e){
			Yii::log("SphinxError:" . var_export($e->getMessage(), true), 'error', 'system.*');
			return array("count" => 0, "data" => null);	
		}
		return array("count" => 0, "data" => null);
    }
    
    
}

?>
